package com.api.zszsj2.util;

import com.alibaba.fastjson.JSONObject;

import java.util.HashMap;
import java.util.Map;

import java.util.*;
import weaver.hrm.HrmUserVarify;
import weaver.hrm.User;
import weaver.general.Util;
import com.api.doc.detail.util.ooxml.commons.DocUtils;
import com.api.doc.detail.util.ooxml.commons.Constant;
import weaver.conn.RecordSet;
import weaver.hrm.company.DepartmentComInfo;
import com.api.zszsj2.util.encodeQR;
import com.api.doc.detail.util.ooxml.commons.CommonUtils;
import com.api.zszsj2.util.HTMLToImage;
import java.io.*;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import weaver.file.util.FileDeleteUtil;
import java.util.List;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
import weaver.general.BaseBean;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.PDFRenderer;
import java.awt.*;
import com.engine.workflow.biz.requestForm.HtmlToPdfBiz;

import com.itextpdf.io.image.PngImageData;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.text.pdf.codec.PngImage;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.Font;
import com.itextpdf.text.Image;
import weaver.hrm.company.SubCompanyComInfo;
public class ImageCardCreator{
    static int targetWidth = 350;
    static int targetHeight = 295;
    static double comprRate = 1.12;

    public static String imageFileToBinaryString(String filwPath){
        // 步骤1：读取图片文件
        File file = new File(filwPath);  // 图片文件路径
        try {
            FileInputStream fis = new FileInputStream(file);  // 创建输入流
            // 步骤2：将图片数据转换为字节数组
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len;
            while ((len = fis.read(buffer)) != -1) {
                bos.write(buffer, 0, len);
            }
            byte[] imageData = bos.toByteArray();

            // 步骤3：将字节数组转换为二进制字符串
            String binaryString = Base64.getEncoder().encodeToString(imageData);
            return binaryString;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }

    //把html写入本地文件
    public static void writeHtmlToFile(String html, String filepath) throws Exception {
        OutputStream os = null;
        OutputStreamWriter write = null;
        BufferedWriter output = null;
        try {
            File file = new File(filepath);
            if (file.exists()) {
                DocUtils.deleteFile(filepath);
            }
            os = new FileOutputStream(file);
            write = new OutputStreamWriter(os, "UTF-8");
            output = new BufferedWriter(write);
            output.write(html);
            output.flush();
        } finally {
            DocUtils.close(os);
            DocUtils.close(write);
            DocUtils.close(output);
        }
        File file = new File(filepath);
        if (!file.exists() || !file.isFile() || file.length() == 0) {
            throw new IOException("save html to file failed");
        }
    }

    public static void PDFToImageConverter(String fromPath,String toPath,int width, int height) throws IOException{
        PDDocument pdf = null;
        BaseBean baseBean = new BaseBean();
        try{
            pdf = PDDocument.load(new File(fromPath));
            PDFRenderer render = new PDFRenderer(pdf);
            for (int pageIndex=0; pageIndex<pdf.getNumberOfPages(); pageIndex++){
                BufferedImage image = render.renderImage(pageIndex);

                baseBean.writeLog("PDFToImageConverter ：getWidth=" + image.getWidth()+", getHeight=" + image.getHeight());
                BufferedImage cut_image = image.getSubimage(36,36,width,height);
                if(toPath.isEmpty() && fromPath.indexOf(".pdf")>fromPath.length()-3){
                    toPath = fromPath.substring(0,fromPath.length()-4);
                }
                ImageIO.write(cut_image,"png", new File(toPath));
//                ImageIO.write(image,"png", new File(toPath+".png"));
            }
        }finally {
            if(pdf!=null)
                pdf.close();
        }
    }

    //ver:horizontal 横条型
    public static void tableToPdf_horizontal(String sybm, String[][] infos, String qrFileName, String htmlPath) throws Exception{
        //todo see: https://blog.csdn.net/double_hll123/article/details/127421837
        BaseBean baseBean = new BaseBean();
        String pdfFile = htmlPath+".pdf";
        String pngFlie = htmlPath+".png";

        int targetWidth = 350;
        int targetHeight = 295;
        double comprRate = 1.12;
        float totalWidth  = Float.valueOf(Double.toString(targetWidth*comprRate));
        float totalHeight  = Float.valueOf(Double.toString(targetHeight*comprRate));


        FileOutputStream fos = new FileOutputStream(pdfFile);
        Document doc = new Document();
        PdfWriter writer = PdfWriter.getInstance(doc,fos);
        writer.setViewerPreferences(PdfWriter.PageModeUseThumbs);
        Rectangle rectangle = new Rectangle(totalWidth, totalHeight);
        writer.setPageSize(rectangle);
        writer.setMargins(0,0,0,0);
        doc.open();

        //90,160,100,
        int column1Width = 100;//约90*comprRate
        int column2Width = 180;//约160*comprRate
        int column3Width = 112;//约100*comprRate
        float[] colWidths = {column1Width, column2Width, column3Width};

        PdfPTable table = new PdfPTable(colWidths);
        table.setTotalWidth(totalWidth);
        table.setHorizontalAlignment(Element.ALIGN_LEFT);

        int borderWidth = 2;
        //部门名称 行
        PdfPCell pCell = new PdfPCell();
        pCell.setColspan(3);
        int[] borderWidths = {borderWidth, borderWidth, borderWidth, borderWidth};
        _setTableStyle_horizontal(table,pCell,Element.ALIGN_CENTER,borderWidths);
        Paragraph paragraph = new Paragraph(sybm,getPdfChineseFont(24,1));
        pCell.setPhrase(paragraph);
        pCell.setPaddingLeft(12);
        pCell.setPaddingRight(12);
        pCell.setFixedHeight(totalHeight/6);
        table.addCell(pCell);

        //内容行
        int fontSize = 18;
        for(int i=0; i<infos.length; i++){
            String[] info = (String[]) infos[i];
            for (int s=0; s<2; s++){
                pCell = new PdfPCell();

                if(s==0) {
                    borderWidths[0] = 0;
                    borderWidths[1] = borderWidth;
                    borderWidths[2] = borderWidth;
                    borderWidths[3] = borderWidth;
                    _setTableStyle_horizontal(table,pCell,Element.ALIGN_CENTER,borderWidths);
                    pCell.setPadding(0);
                    paragraph = new Paragraph(info[s],getPdfChineseFont(fontSize,0));
                    pCell.setPhrase(paragraph);
                    table.addCell(pCell);
                }else if(s==1) {
                    //除了最后两行，其他都合并两列
                    if(i<infos.length-2) {
                        pCell.setColspan(2);
                        borderWidths[0] = 0;
                        borderWidths[1] = borderWidth;
                        borderWidths[2] = borderWidth;
                        borderWidths[3] = 0;
                        _setTableStyle_horizontal(table, pCell, Element.ALIGN_LEFT, borderWidths);
                        pCell.setPaddingLeft(12);
                        pCell.setPaddingRight(12);
                        paragraph = new Paragraph(info[s],getPdfChineseFont(fontSize,0));
                        pCell.setPhrase(paragraph);
                        table.addCell(pCell);
                    }
                    else{
                        borderWidths[0] = 0;
                        borderWidths[1] = borderWidth;
                        borderWidths[2] = borderWidth;
                        borderWidths[3] = 0;
                        _setTableStyle_horizontal(table, pCell, Element.ALIGN_LEFT, borderWidths);
                        pCell.setPaddingLeft(12);
                        pCell.setPaddingRight(12);
                        paragraph = new Paragraph(info[s],getPdfChineseFont(fontSize,0));
                        pCell.setPhrase(paragraph);
                        table.addCell(pCell);
                        if(i==infos.length-2){
                            //倒数第二行，二维码
                            pCell = new PdfPCell();
                            pCell.setRowspan(2);
                            borderWidths[0] = 0;
                            borderWidths[1] = borderWidth;
                            borderWidths[2] = borderWidth;
                            borderWidths[3] = 0;
                            _setTableStyle_horizontal(table,pCell,Element.ALIGN_CENTER,borderWidths);
                            _addImageToCell(pCell,qrFileName,column3Width);
                            table.addCell(pCell);
                        }
                    }
                }
            }
        }

        doc.add(table);
        doc.close();
        PDFToImageConverter(pdfFile,pngFlie,(int)totalWidth,(int)totalHeight);
        DocUtils.deleteFile(pdfFile);
    }

    private static void  _setTableStyle_horizontal(PdfPTable table,PdfPCell cell, int align, int[] borderWidths){
        int targetWidth = 350;
        int targetHeight = 295;
        double comprRate = 1.12;
        float totalWidth  = Float.valueOf(Double.toString(targetWidth*comprRate));
        float totalHeight  = Float.valueOf(Double.toString(targetHeight*comprRate));

        table.setLockedWidth(true);
        table.setTotalWidth(totalWidth);
        table.setHorizontalAlignment(Element.ALIGN_LEFT);

        cell.setMinimumHeight(totalHeight/6);
        cell.setFixedHeight(totalHeight/6);
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);//垂直对齐方式
        if(align>0){
            cell.setHorizontalAlignment(align);//水平对齐方式
        }else{
            cell.setHorizontalAlignment(Element.ALIGN_LEFT);//水平对齐方式
        }
        cell.setBackgroundColor(BaseColor.WHITE);
        cell.setBorder(1);
        cell.setBorderWidth(1);
        cell.setBorderWidthTop(borderWidths[0]);
        cell.setBorderWidthRight(borderWidths[1]);
        cell.setBorderWidthBottom(borderWidths[2]);
        cell.setBorderWidthLeft(borderWidths[3]);
        cell.setBorderColor(BaseColor.BLACK);
        cell.setPadding(0);
    }

    private static Font getPdfChineseFont(Integer fontSize, Integer isBlod) throws Exception{
        if(fontSize == null)
            fontSize = 12;
        String configpath = "/font";
        String rootpath = HtmlToPdfBiz.getSystemDir();
        String fontsPath = rootpath + configpath;

//        BaseFont bsFont = BaseFont.createFont(fontsPath+"/msyh.ttf",BaseFont.IDENTITY_H,BaseFont.NOT_EMBEDDED);
        BaseFont bsFont = BaseFont.createFont(fontsPath+"/simsun.ttc,0",BaseFont.IDENTITY_H,BaseFont.NOT_EMBEDDED);
        Font fontChinese = new Font(bsFont, 12, isBlod);
        fontChinese.setColor(BaseColor.BLACK);
        fontChinese.setSize(fontSize);
        return fontChinese;
    }

    private static void _addImageToCell(PdfPCell cell, String imagePath, int height) throws Exception{
        File file = new File(imagePath);  // 图片文件路径
        try {
            Image jpg = PngImage.getImage(imagePath);
            cell.setImage(jpg);
            cell.setFixedHeight(height);
            cell.setPaddingTop(10);
            cell.setPaddingBottom(1);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}